import { Channel, UserChannelResponse } from '@/types/data'
import { RootThunkAction } from '@/types/store'
import { AllChannelsResponse, ArticlesResponse } from '@/types/data'
import { http } from '@/utils/http'
import differenceBy from 'lodash/differenceBy'

const CHANNEL_KEY = 'geek-channels'

//获取用户当前频道
export const getUserChannel = (): RootThunkAction => {
	return async (dispatch, getState) => {
		/*
      1. 在该 action 中，判断用户是否登录
      2. 如果已登录，发送请求获取用户的频道列表数据
      3. 如果未登录，先判断本地缓存中有没有频道列表数据
      4. 如果有，拿到本地的频道列表数据
      5. 如果没有，就发送请求获取默认的频道列表数据，并存储到本地缓存中
    */
		const {
			login: { token },
		} = getState()
		let userChannel: Channel[] = []

		//判断用户是否登录
		if (token) {
			// 登录
			const res = await http.get<UserChannelResponse>('/user/channels')
			const { channels } = res.data.data
			// console.log('登录', channels)
			userChannel = channels
		} else {
			// 未登录
			const localChannels = JSON.parse(
				localStorage.getItem(CHANNEL_KEY) ?? '[]'
			) as Channel[]
			if (localChannels.length > 0) {
				// 有
				// console.log('未登录，本地有', localChannels)
				userChannel = localChannels
			} else {
				// 没有
				const res = await http.get<UserChannelResponse>(
					'/user/channels'
				)
				const { channels } = res.data.data
				localStorage.setItem(CHANNEL_KEY, JSON.stringify(channels))
				// console.log('未登录，本地没有', channels)
				userChannel = channels
			}
		}
		dispatch({ type: 'home/getUserChannel', payload: userChannel })
	}
}

//获取频道推荐（可选频道）
export const getAllChannel = (): RootThunkAction => {
	return async (dispatch, getState) => {
		const res = await http.get<AllChannelsResponse>('channels')
		const {
			home: { userChannel },
		} = getState()
		const restChannels = differenceBy(
			res.data.data.channels,
			userChannel,
			'id'
		)

		dispatch({ type: 'home/getAllChannel', payload: restChannels })
	}
}

//删除频道（可选频道）
export const delChannel = (channel: Channel): RootThunkAction => {
	return async (dispatch, getState) => {
		const {
			login: { token },
		} = getState()

		if (token) {
			// 已登录
			await http.delete(`/user/channels/${channel.id}`)
		} else {
			// 如果未登录，就删除本地的数据
			// 从本地缓存中取出 频道数据
			const localChannels = JSON.parse(
				localStorage.getItem(CHANNEL_KEY) ?? '[]'
			) as Channel[]

			// 然后，从频道数据中，删除该项，然后，存回到本地缓存中
			const userChannel = localChannels.filter(
				(item) => item.id !== channel.id
			)
			localStorage.setItem(CHANNEL_KEY, JSON.stringify(userChannel))
		}

		dispatch({ type: 'home/delChannel', payload: channel })
	}
}

//添加频道
export const addChannel = (channel: Channel): RootThunkAction => {
	return async (dispatch, getState) => {
		const {
			login: { token },
		} = getState()

		if (token) {
			// 已登录
			await http.patch('/user/channels', [channel])
		} else {
			// 从本地缓存中取出 频道数据
			const localChannels = JSON.parse(
				localStorage.getItem(CHANNEL_KEY) ?? '[]'
			) as Channel[]

			// 然后，从频道数据中，删除该项，然后，存回到本地缓存中
			const userChannel = [...localChannels, channel]
			localStorage.setItem(CHANNEL_KEY, JSON.stringify(userChannel))
		}

		dispatch({ type: 'home/addChannel', payload: channel })
	}
}

//频道列表
export const getArticleList = (
	channel_id: number,
	timestamp: string | null
): RootThunkAction => {
	return async (dispatch) => {
		const res = await http.get<ArticlesResponse>('/articles', {
			params: {
				channel_id,
				timestamp,
			},
		})
		dispatch({
			type: 'home/getChannelArticles',
			payload: {
				channelId: channel_id,
				data: res.data.data,
			},
		})
	}
}


